<script setup lang="ts">
import { PivotTable, VTable } from '@visactor/vue-vtable'
import { downloadExcel, exportVTableToExcel } from '@visactor/vtable-export'
import html2canvas from 'html2canvas'
import { Message } from '@arco-design/web-vue'
import { ClassScheduleApi } from '@/apis'
import { useDictLabel, useForm, useTable } from '@/hooks'

defineOptions({
  name: 'ClassScheduleTable',
})

const router = useRouter()

const { form } = useForm<ClassScheduleApi.ClassShecduleQuery>({
  classYear: new Date().getFullYear(),
  term: 'SPRING',
  grade: ['grade1'],
  subject: undefined,
  classroomId: undefined,
  campusId: undefined,
  className: undefined,
  saleStatus: [1],
  classCategory: [1],
  classTypeId: undefined,
})

let arrangeTemplateMap = {}
let timeTemplateMap = {}
// let columnTree: any[] = []
const {
  tableData,
  loading,
  search,
} = useTable(() => ClassScheduleApi.getClassShecdule(form), {
  immediate: false,
  onSuccess: () => {
    arrangeTemplateMap = {}
    timeTemplateMap = {}
    // columnTree = []

    tableData.value.forEach((item) => {
      arrangeTemplateMap[item.arrangeTemplateId] = item.arrangeTemplate
      timeTemplateMap[item.timeTemplateId] = item.timeTemplate
    })

    tableData.value.sort((a, b) => {
      if (arrangeTemplateMap[a.arrangeTemplateId].id === arrangeTemplateMap[b.arrangeTemplateId].id) {
        return timeTemplateMap[a.timeTemplateId].startTime > timeTemplateMap[b.timeTemplateId].startTime ? 1 : -1
      } else {
        return arrangeTemplateMap[a.arrangeTemplateId].name > arrangeTemplateMap[b.arrangeTemplateId].name ? 1 : -1
      }
      // return new Date(arrangeTemplateMap[a.arrangeTemplateId].startDate) > new Date(arrangeTemplateMap[b.arrangeTemplateId].startDate) ? 1 : -1
    })

    // tableData.value.forEach((item) => {
    //   let arrange = columnTree.find(arrange => arrange.value === item.arrangeTemplateId)
    //   if (!arrange) {
    //     arrange = {
    //       dimensionKey: 'arrangeTemplateId',
    //       value: item.arrangeTemplateId,
    //       children: [],
    //     }
    //     columnTree.push(arrange)
    //   }

    //   let time = arrange.children.find(time => time.value === item.timeTemplateId)
    //   if (!time) {
    //     time = {
    //       dimensionKey: 'timeTemplateId',
    //       value: item.timeTemplateId,
    //       children: [
    //         { indicatorKey: 'id' },
    //       ],

    //     }
    //     arrange.children.push(time)
    //   }
    // })

    // console.log('xx: ', columnTree)

    // pivotTableRef.value.vTableInstance.updateOption({
    //   columnTree,
    // })
    // pivotTableRef.value.vTableInstance.updateSortRules([
    //   { sortField: 'arrangeTemplateId', sortType: 'ASC', sortFunc: (a, b) => {
    //     return new Date(arrangeTemplateMap[a].startDate) > new Date(arrangeTemplateMap[b].startDate) ? 1 : -1
    //   } },
    //   // { sortField: 'timeTemplateId', sortType: 'ASC', sortFunc: (a, b) => {
    //   //   console.log('xxx')
    //   //   return timeTemplateMap[a].startTime > timeTemplateMap[b].startTime ? 1 : -1
    //   // } },
    // ])
    // nextTick(() => {
    //   console.log(pivotTableRef.value.vTableInstance.dataset.colHeaderTree)
    //   pivotTableRef.value.vTableInstance.dataset.colHeaderTree.sort((a, b) => {
    //     console.log(a, b)
    //     return new Date(arrangeTemplateMap[a.value].startDate) > new Date(arrangeTemplateMap[b.value].startDate) ? 1 : -1
    //   })
    //   pivotTableRef.value.vTableInstance.dataset.colHeaderTree.forEach((element) => {
    //     console.log('xx: ', element)
    //     element.children.sort((a, b) => {
    //       return timeTemplateMap[a.value].startTime > timeTemplateMap[b.value].startTime ? 1 : -1
    //     })
    //   })
    //   console.log(pivotTableRef.value.vTableInstance.dataset.colHeaderTree)
    // })
  },
})

const showFullClass = ref(false)
const records = computed(() => {
  if (showFullClass.value) {
    return tableData.value
  } else {
    return tableData.value.filter(item => item.remainCount > 0)
  }
})

const getColor = (record) => {
  if (!record.id) {
    return undefined
  } else if (record.remainCount <= 0) {
    return '#FC9090'
  } else if (record.remainCount <= 1) {
    return '#FFB380'
  } else if (record.remainCount <= 2) {
    return '#FFF188'
  } else {
    return '#A1E2C7'
  }
}

const getTitle = (record) => {
  if (record.remainCount <= 0) {
    return `${record.classTypeName}(已满)`
  } else if (record.remainCount <= 2) {
    return `${record.classTypeName}(余${record.remainCount})`
  } else if (record.remainCount > 2) {
    return `${record.classTypeName}`
  }
}

const pivotTableRef = ref<InstanceType<typeof PivotTable>>()

const options = {
  title: {
    text: '班级课表',
    align: 'center',
    padding: [0, 0, 20, 0],
    textStyle: {

    },
  },
  emptyTip: {
    text: '选择查询条件后点击搜索',
  },
  widthMode: 'autoWidth',
  heightMode: 'autoHeight',
  autoFillWidth: true,
  // autoFillHeight: true,
  theme: VTable.themes.ARCO.extends({
    bodyStyle: {
      borderLineWidth: 1,
    },
  }),
  hover: {
    highlightMode: 'row',
  },
  enableLineBreak: true,
  hideIndicatorName: true,
  rows: [
    {
      dimensionKey: 'leadTeacherName',
      title: '老师',
      headerStyle: {
        textStick: true,
        fontSize: 14,
        fontWeight: 500,
        textAlign: 'left',
      },
      width: 'auto',
    },
  ],
  columns: [
    {
      dimensionKey: 'arrangeTemplateId',
      title: '期段',
      headerStyle: {
        textStick: true,
        textAlign: 'center',
      },
      headerFormat: (title) => {
        // return `${arrangeTemplateMap[title].fullName}\n${arrangeTemplateMap[title].startDate}`
        return arrangeTemplateMap[title].fullName
      },
      // sort: true,
      width: 'auto',
    },
    {
      dimensionKey: 'timeTemplateId',
      title: '时间段',
      headerStyle: {
        textStick: true,
        textAlign: 'center',
      },
      headerFormat: (title) => {
        return timeTemplateMap[title].name
      },
      // sort: true,
      width: 'auto',
    },
  ],
  indicators: [
    {
      indicatorKey: 'id',
      title: '班级',
      format: (value, col, row, table) => {
        if (value) {
          const record = table.getRecordByRowCol(col, row)
          return `${record[0].campusName}\n${record[0].classTypeName}`
        }
      },
      customLayout: (args) => {
        const { table, row, col, rect } = args
        const record = (table.getCellOriginRecord(col, row) || [{}])[0]
        const { height, width } = rect ?? table.getCellRect(col, row)
        const rootContainer = new VTable.CustomLayout.Group({
          height,
          width,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          flexWrap: 'nowrap',
          cursor: 'pointer',
        })
        const contentContainer = new VTable.CustomLayout.Group({
          height: height - 8,
          width: width - 8,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          flexWrap: 'nowrap',
          background: getColor(record),
          // fill: 'white',
          // opacity: 0.5,
          boundsPadding: 8,
          cornerRadius: 8,
          // baseOpacity: 0.8,
          cursor: 'pointer',
        })

        const typeName = new VTable.CustomLayout.Text({
          text: getTitle(record),
          fontSize: 15,
          fontWeight: 500,
          // opacity: 0.8,
          marginBottom: 10,
          fill: '#222',
          cursor: 'pointer',
        })

        const campusName = new VTable.CustomLayout.Text({
          text: record.campusName,
          fontSize: 13,
          fill: '#444',
          cursor: 'pointer',
        })
        rootContainer.add(contentContainer)
        contentContainer.add(typeName)
        contentContainer.add(campusName)
        return {
          rootContainer,
          renderDefault: false,
          enableCellPadding: false,
        }
      },
    },
  ],
  corner: {
    titleOnDimension: 'none',
  },
  dataConfig: {
    // 排序规则
    sortRules: [
      // { sortField: 'arrangeTemplateId', sortType: 'ASC', sortFunc: (a, b) => {
      //   return new Date(arrangeTemplateMap[a].startDate) > new Date(arrangeTemplateMap[b].startDate) ? 1 : -1
      // } },
      // { sortField: 'timeTemplateId', sortType: 'ASC', sortFunc: (a, b) => {
      //   return timeTemplateMap[a].startTime > timeTemplateMap[b].startTime ? 1 : -1
      // } },
    ],
  },
}

const tableName = computed(() => {
  return `${form.classYear}${useDictLabel('TermEnum', form.term, '')}${(useDictLabel('Grade', form.grade, ''))}${(useDictLabel('Subject', form.subject, ''))}排课表`
})

const onSearch = async () => {
  search()
  options.title.text = tableName.value
  pivotTableRef.value?.tableInstance?.updateOption({
    ...options,
  })
}

const onExportExcel = async () => {
  const excelOption = {
  }
  downloadExcel(await exportVTableToExcel(pivotTableRef.value?.vTableInstance, excelOption), '班级排课情况')
}

const onExportImage = () => {
  // pivotTableRef.value.vTableInstance.exportImg()
  const table = document.getElementById('table')!
  html2canvas(table).then((res) => {
    const imgUrl = res.toDataURL('image/png')
    const aLink = document.createElement('a')
    aLink.href = imgUrl
    aLink.download = '班级课表.png'
    document.body.appendChild(aLink)
    aLink.click()
    document.body.removeChild(aLink)
    setTimeout(() => {
      Message.success('导出图片成功')
    }, 10)
  })
}

const gotoClassDetail = (id) => {
  router.push({ path: '/education/class/detail', query: { id } })
}

onMounted(() => {
  pivotTableRef.value?.vTableInstance?.on('dblclick_cell', (args) => {
    if (args.originData && args.originData.length > 0 && args.originData[0]?.id) {
      gotoClassDetail(args.originData[0]?.id)
    }
  })
})
</script>

<template>
  <ProPage title="班级课表" :flex-table="false" :loading="loading" description="展示班级排课情况，数据为实时">
    <template #extra>
      <a-space>
        <a-button type="outline" @click="onExportExcel">
          导出excel
        </a-button>
        <a-button type="primary" @click="onExportImage">
          导出图片
        </a-button>
      </a-space>
    </template>
    <a-space direction="vertical" size="medium">
      <a-space>
        <label class="label">学期年级</label>
        <YearTermCascader v-model:class-year="form.classYear" v-model:term="form.term" class="!min-w-150px" check-strictly />
        <DictSelect v-model="form.grade" type="select" code="Grade" placeholder="年级" class="!min-w-150px" multiple />
        <DictSelect v-model="form.subject" type="select" code="Subject" placeholder="科目" class="!min-w-150px" />
        <a-button type="primary" @click="onSearch">
          搜索
        </a-button>
      </a-space>

      <a-space>
        <label class="label">其他条件</label>
        <EmployeeSelect v-model="form.leadTeacherId" type="LEAD_TEACHER" placeholder="主讲老师" class="!min-w-150px" multiple />
        <ClassTypeSelect v-model="form.classTypeId" placeholder="班型" class="!min-w-150px" />
        <DictSelect v-model="form.classCategory" type="select" code="ClassCategoryEnum" placeholder="类别" class="!min-w-150px" multiple />
        <ClassroomCascader v-model:campus-id="form.campusId" v-model:classroom-id="form.classroomId" class="!min-w-150px" check-strictly />
        <DictSelect v-model="form.saleStatus" type="checkbox" code="SaleStatusEnum" />
        <label class="label">展示满班</label>
        <DictSelect v-model="showFullClass" type="boolean" />
      </a-space>
      <!-- <a-space>
        <label class="label">展示</label>
        <EmployeeSelect v-model="form.leadTeacherId" type="LEAD_TEACHER" placeholder="主讲老师" class="!min-w-150px" multiple />
        <DictSelect v-model="form.classCategory" type="select" code="ClassCategoryEnum" placeholder="类别" class="!min-w-150px" multiple />
        <ClassroomCascader v-model:campus-id="form.campusId" v-model:classroom-id="form.classroomId" class="!min-w-150px" check-strictly />
        <DictSelect v-model="form.saleStatus" type="checkbox" code="SaleStatusEnum" />
        <label class="label">展示满班</label>
        <DictSelect v-model="showFullClass" type="boolean" />
      </a-space> -->
    </a-space>
    <a-divider />
    <div id="table" class="h-1200px">
      <PivotTable ref="pivotTableRef" :options="options" :records="records" />
    </div>
  </ProPage>
</template>

<style lang="less" scoped>
.label {
  display: inline-block;
  width: 60px;
  text-align: right;
  flex-shrink: 0;
  margin-right: 10px;
  color: var(--color-text-1);
}
</style>
